package com.geek.factory.controller;

import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.dto.DeviceRepairDTO;
import com.geek.factory.entity.DeviceRepair;
import com.geek.factory.result.Result;
import com.geek.factory.service.DeviceRepairService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/repair")
public class DeviceRepairController {


    @Resource
    private DeviceRepairService deviceRepairService;

    /**
     * ✅ 查询所有设备维修记录（包含产线名）
     */
    @GetMapping("/list")
    public Result list() {
        List<DeviceRepairDTO> list = deviceRepairService.getAllWithLineName();
        return new Result(SuccessConstant.SUCCESS, "查询成功", list);
    }

    /**
     * ✅ 根据ID查询单个设备维修
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        DeviceRepair repair = deviceRepairService.getById(id);
        if (repair != null) {
            return new Result(SuccessConstant.SUCCESS, "查询成功", repair);
        }
        return new Result(SuccessConstant.FAIL, "未找到该维修记录");
    }

    /**
     * ✅ 新增维修记录
     */
    @PostMapping("/add")
    public Result add(@RequestBody DeviceRepair repair) {
        boolean saved = deviceRepairService.save(repair);
        if (saved) {
            return new Result(SuccessConstant.SUCCESS, "新增成功");
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    /**
     * ✅ 更新维修记录
     */
    @PutMapping("/update")
    public Result update(@RequestBody DeviceRepair repair) {
        boolean updated = deviceRepairService.updateById(repair);
        if (updated) {
            return new Result(SuccessConstant.SUCCESS, "修改成功");
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    /**
     * ✅ 删除维修记录
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean removed = deviceRepairService.removeById(id);
        if (removed) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    /**
     * ✅ 获取产线名称（新增时根据 productLineId 使用）
     */
    @GetMapping("/line-name/{productLineId}")
    public Result getLineName(@PathVariable Long productLineId) {
        String name = deviceRepairService.getLineNameByProductLineId(productLineId);
        return new Result(SuccessConstant.SUCCESS, "查询成功", name);
    }


}
